
import { useState } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Label } from "@/components/ui/label";
import { Progress } from "@/components/ui/progress";
import { ChevronDown, ChevronUp, Brain, Star, Compass, CheckCircle, ExternalLink, RotateCcw, Trophy, Clock, RefreshCw, FileDown, Download, Users, Bookmark } from "lucide-react";

interface AssessmentResult {
  status: 'not-started' | 'in-progress' | 'completed';
  result?: string;
  description?: string;
  completedDate?: string;
  details?: string[];
}

interface AssessmentResults {
  learningStyle: AssessmentResult;
  strengths: AssessmentResult;
  interests: AssessmentResult;
}

export function PersonalizedLearningInsights() {
  const [results, setResults] = useState<AssessmentResults>({
    learningStyle: { 
      status: 'completed',
      result: 'Visual Learner',
      description: 'You learn best through visual aids, diagrams, and charts.',
      completedDate: 'March 15, 2025'
    },
    strengths: { 
      status: 'completed',
      result: 'Creative Contributor',
      description: 'You excel at generating innovative ideas and solutions.',
      completedDate: 'March 12, 2025',
      details: ['Creative Problem Solving', 'Analytical Thinking', 'Collaboration']
    },
    interests: { status: 'not-started' }
  });
  
  const [expandedCards, setExpandedCards] = useState<Record<string, boolean>>({
    learningStyle: false,
    strengths: false,
    interests: false
  });

  const toggleCard = (card: string) => {
    setExpandedCards(prev => ({
      ...prev,
      [card]: !prev[card]
    }));
  };

  const handleAssessmentComplete = (type: keyof AssessmentResults, result: string, description: string, details?: string[]) => {
    setResults(prev => ({
      ...prev,
      [type]: {
        status: 'completed',
        result,
        description,
        completedDate: new Date().toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' }),
        details
      }
    }));
  };

  const handleRetake = (type: keyof AssessmentResults) => {
    setResults(prev => ({
      ...prev,
      [type]: { status: 'not-started' }
    }));
  };

  const handleRetakeAll = () => {
    setResults({
      learningStyle: { status: 'not-started' },
      strengths: { status: 'not-started' },
      interests: { status: 'not-started' }
    });
  };

  // Calculate progress
  const completedCount = Object.values(results).filter(result => result.status === 'completed').length;
  const totalCount = Object.keys(results).length;
  const progressPercentage = (completedCount / totalCount) * 100;
  const isAllCompleted = completedCount === totalCount;

  // Get recommended groups based on completed assessments
  const getRecommendedGroups = () => {
    const groups = [];
    if (results.learningStyle.status === 'completed' && results.learningStyle.result?.includes('Visual')) {
      groups.push({
        name: 'Visual Study Masters',
        description: 'A community focused on visual learning techniques and methods',
        tags: ['#visual', '#diagrams', '#mind-maps'],
        members: 89,
        matchReason: 'Matches your Visual learning style'
      });
    }
    if (results.strengths.status === 'completed' && results.strengths.result?.includes('Creative')) {
      groups.push({
        name: 'Creative Project Lab',
        description: 'Collaborative space for innovative ideas and creative solutions',
        tags: ['#creative', '#innovation', '#collaboration'],
        members: 124,
        matchReason: 'Perfect for Creative Contributors'
      });
    }
    if (results.interests.status === 'completed') {
      groups.push({
        name: 'Interest Explorer Club',
        description: 'Discover new passions and connect with like-minded learners',
        tags: ['#exploration', '#interests', '#discovery'],
        members: 156,
        matchReason: 'Aligns with your interest profile'
      });
    }
    return groups;
  };

  const assessmentCards = [
    {
      key: 'learningStyle',
      title: 'Learning Style Profiler',
      subtitle: 'Discover how you learn best',
      icon: Brain,
      component: LearningStyleAssessment
    },
    {
      key: 'strengths',
      title: 'Strengths Discovery',
      subtitle: 'Identify your academic and cognitive strengths',
      icon: Star,
      component: StrengthsDiscoveryAssessment
    },
    {
      key: 'interests',
      title: 'Interest Explorer',
      subtitle: 'Match your interests with learning pathways',
      icon: Compass,
      component: InterestExplorerAssessment
    }
  ];

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'completed': return 'bg-green-100 text-green-700 border-green-200';
      case 'in-progress': return 'bg-orange-100 text-orange-700 border-orange-200';
      case 'not-started': return 'bg-gray-100 text-gray-700 border-gray-200';
      default: return 'bg-gray-100 text-gray-700 border-gray-200';
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'completed': return '✅';
      case 'in-progress': return '🟠';
      case 'not-started': return '⚪️';
      default: return '⚪️';
    }
  };

  return (
    <div className="space-y-8">
      {/* Progress Summary Card */}
      <Card className="bg-gradient-to-r from-blue-50 to-purple-50 border-blue-100">
        <CardContent className="p-8">
          <div className="text-center space-y-6">
            <div className="space-y-2">
              <h1 className="text-3xl font-bold bg-gradient-to-r from-blue-500 to-purple-600 bg-clip-text text-transparent flex items-center justify-center gap-3">
                <Trophy className="w-8 h-8 text-yellow-500" />
                Self-Discovery Progress
              </h1>
              <p className="text-gray-600 text-lg max-w-2xl mx-auto">
                Track your learning profile and unlock group recommendations based on your strengths and interests.
              </p>
            </div>
            
            <div className="max-w-md mx-auto space-y-4">
              <div className="flex items-center justify-between text-sm font-medium text-gray-700">
                <span>{completedCount} of {totalCount} assessments completed</span>
                <span className="text-blue-600">{Math.round(progressPercentage)}% Complete</span>
              </div>
              <Progress value={progressPercentage} className="h-3" />
              <Button 
                variant="outline" 
                onClick={handleRetakeAll}
                className="w-full text-blue-600 border-blue-200 hover:bg-blue-50"
              >
                <RefreshCw className="w-4 h-4 mr-2" />
                Retake All Assessments
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Assessment Cards */}
      <div className="space-y-6">
        {assessmentCards.map((assessment) => {
          const result = results[assessment.key as keyof AssessmentResults];
          const Icon = assessment.icon;
          const isExpanded = expandedCards[assessment.key];
          
          return (
            <Card key={assessment.key} className="bg-white shadow-sm border-gray-100 hover:shadow-md transition-all duration-200" style={{ minHeight: '120px' }}>
              <Collapsible open={isExpanded} onOpenChange={() => toggleCard(assessment.key)}>
                <CollapsibleTrigger asChild>
                  <CardHeader className="cursor-pointer hover:bg-gray-50/50 transition-colors">
                    <div className="flex items-center justify-between">
                      {/* Left: Icon + Title + Subtitle */}
                      <div className="flex items-center gap-4">
                        <div className="p-3 rounded-lg bg-blue-50">
                          <Icon className="w-6 h-6 text-blue-600" />
                        </div>
                        <div>
                          <CardTitle className="text-xl font-semibold text-gray-900">{assessment.title}</CardTitle>
                          <CardDescription className="text-gray-600 mt-1">{assessment.subtitle}</CardDescription>
                        </div>
                      </div>

                      {/* Center: Status + Results */}
                      <div className="flex flex-col items-center gap-2 min-w-[200px]">
                        <Badge className={`${getStatusColor(result.status)} border text-sm px-3 py-1`}>
                          <span className="mr-2">{getStatusIcon(result.status)}</span>
                          {result.status.charAt(0).toUpperCase() + result.status.slice(1).replace('-', ' ')}
                        </Badge>
                        
                        {result.result && (
                          <Badge variant="outline" className="text-blue-600 border-blue-200 text-sm">
                            {result.result}
                          </Badge>
                        )}
                        
                        {result.completedDate && (
                          <p className="text-xs text-gray-500">
                            Last completed on {result.completedDate}
                          </p>
                        )}
                      </div>

                      {/* Right: Action Button + Expand */}
                      <div className="flex items-center gap-3">
                        {result.status === 'completed' ? (
                          <Button 
                            size="sm" 
                            variant="outline"
                            onClick={(e) => { e.stopPropagation(); handleRetake(assessment.key as keyof AssessmentResults); }}
                            className="text-blue-600 border-blue-200 hover:bg-blue-50"
                          >
                            Retake
                          </Button>
                        ) : (
                          <Button 
                            size="sm"
                            onClick={(e) => { e.stopPropagation(); toggleCard(assessment.key); }}
                            className="bg-gradient-to-r from-blue-500 to-purple-600 hover:from-blue-600 hover:to-purple-700 text-white"
                          >
                            Start
                          </Button>
                        )}
                        <ChevronDown className={`w-5 h-5 text-gray-400 transition-transform ${isExpanded ? 'rotate-180' : ''}`} />
                      </div>
                    </div>
                  </CardHeader>
                </CollapsibleTrigger>
                
                <CollapsibleContent>
                  <CardContent className="pt-0 pb-6">
                    {result.status === 'completed' ? (
                      <div className="space-y-4">
                        <div className="bg-blue-50 p-4 rounded-lg">
                          <h4 className="font-semibold text-blue-900">{result.result}</h4>
                          <p className="text-blue-700 text-sm mt-1">{result.description}</p>
                          {result.details && (
                            <div className="flex flex-wrap gap-2 mt-3">
                              {result.details.map((detail, index) => (
                                <Badge key={index} variant="secondary" className="text-blue-800 bg-blue-100 text-xs">
                                  {detail}
                                </Badge>
                              ))}
                            </div>
                          )}
                        </div>
                        
                        <div className="flex gap-2">
                          <Button variant="outline" size="sm" className="flex-1">
                            <ExternalLink className="w-3 h-3 mr-1" />
                            View Full Report
                          </Button>
                        </div>
                      </div>
                    ) : (
                      <assessment.component onComplete={(result: string, description: string, details?: string[]) => 
                        handleAssessmentComplete(assessment.key as keyof AssessmentResults, result, description, details)
                      } />
                    )}
                  </CardContent>
                </CollapsibleContent>
              </Collapsible>
            </Card>
          );
        })}
      </div>

      {/* Group Recommendations Section */}
      {completedCount > 0 && (
        <div className="bg-blue-50/50 p-8 rounded-2xl border border-blue-100">
          <div className="text-center mb-6">
            <h2 className="text-2xl font-bold text-gray-900 mb-2 flex items-center justify-center gap-2">
              🎯 Recommended for You
            </h2>
            <p className="text-gray-600">
              Based on your completed assessments, we recommend joining these groups:
            </p>
          </div>
          
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
            {getRecommendedGroups().map((group, index) => (
              <Card key={index} className="bg-white shadow-sm hover:shadow-md transition-all duration-200 group cursor-pointer">
                <CardContent className="p-4">
                  <div className="flex items-start justify-between mb-3">
                    <div>
                      <h4 className="font-semibold text-gray-900 group-hover:text-blue-600 transition-colors">
                        {group.name}
                      </h4>
                      <p className="text-sm text-gray-600 mt-1">{group.description}</p>
                    </div>
                    <Button variant="ghost" size="sm" className="p-1 opacity-0 group-hover:opacity-100 transition-opacity">
                      <Bookmark className="w-4 h-4" />
                    </Button>
                  </div>
                  
                  <div className="flex flex-wrap gap-2 mb-3">
                    {group.tags.map((tag, tagIndex) => (
                      <Badge key={tagIndex} variant="secondary" className="text-xs">
                        {tag}
                      </Badge>
                    ))}
                  </div>
                  
                  <div className="flex items-center justify-between mb-3">
                    <span className="text-sm text-gray-600">{group.members} members</span>
                    <Badge variant="outline" className="text-xs text-green-600 border-green-200">
                      {group.matchReason}
                    </Badge>
                  </div>
                  
                  <Button size="sm" className="w-full bg-gradient-to-r from-blue-500 to-purple-600 hover:from-blue-600 hover:to-purple-700 text-white">
                    <Users className="w-4 h-4 mr-2" />
                    Join Group
                  </Button>
                </CardContent>
              </Card>
            ))}
          </div>
          
          <div className="text-center">
            <Button className="bg-gradient-to-r from-blue-500 to-purple-600 hover:from-blue-600 hover:to-purple-700 text-white">
              <ExternalLink className="w-4 h-4 mr-2" />
              Explore All Groups
            </Button>
          </div>
        </div>
      )}

      {/* Export Option */}
      {isAllCompleted && (
        <div className="text-center">
          <Button variant="outline" className="gap-2">
            <Download className="w-4 h-4" />
            Export Profile Insights to PDF
          </Button>
        </div>
      )}
    </div>
  );
}

// Simple Learning Style Assessment Component
function LearningStyleAssessment({ onComplete }: { onComplete: (result: string, description: string) => void }) {
  const [currentQuestion, setCurrentQuestion] = useState(0);
  const [answers, setAnswers] = useState<string[]>([]);

  const questions = [
    {
      question: "When studying new material, I prefer to:",
      options: [
        { value: "visual", label: "Watch videos or diagrams" },
        { value: "auditory", label: "Listen to lectures or podcasts" },
        { value: "kinesthetic", label: "Use hands-on exercises" },
        { value: "read-write", label: "Read and take notes" }
      ]
    },
    {
      question: "I remember things better when:",
      options: [
        { value: "visual", label: "I see them" },
        { value: "auditory", label: "I hear them" },
        { value: "kinesthetic", label: "I do them" },
        { value: "read-write", label: "I write them down" }
      ]
    },
    {
      question: "When learning something new, I prefer:",
      options: [
        { value: "visual", label: "Charts and graphs" },
        { value: "auditory", label: "Discussion and explanation" },
        { value: "kinesthetic", label: "Practice and experimentation" },
        { value: "read-write", label: "Lists and written instructions" }
      ]
    },
    {
      question: "My ideal study environment includes:",
      options: [
        { value: "visual", label: "Visual aids and colorful materials" },
        { value: "auditory", label: "Background music or sounds" },
        { value: "kinesthetic", label: "Space to move around" },
        { value: "read-write", label: "Quiet space with books and notes" }
      ]
    },
    {
      question: "When I need to concentrate, I:",
      options: [
        { value: "visual", label: "Use highlighters and visual organizers" },
        { value: "auditory", label: "Talk through problems aloud" },
        { value: "kinesthetic", label: "Take breaks to move around" },
        { value: "read-write", label: "Make detailed written notes" }
      ]
    }
  ];

  const handleAnswer = (value: string) => {
    const newAnswers = [...answers];
    newAnswers[currentQuestion] = value;
    setAnswers(newAnswers);

    if (currentQuestion < questions.length - 1) {
      setCurrentQuestion(currentQuestion + 1);
    } else {
      // Calculate result
      const counts = { visual: 0, auditory: 0, kinesthetic: 0, 'read-write': 0 };
      newAnswers.forEach(answer => {
        if (answer in counts) {
          counts[answer as keyof typeof counts]++;
        }
      });
      
      const topStyle = Object.entries(counts).reduce((a, b) => counts[a[0] as keyof typeof counts] > counts[b[0] as keyof typeof counts] ? a : b)[0];
      const styleLabels = {
        visual: 'Visual Learner',
        auditory: 'Auditory Learner', 
        kinesthetic: 'Kinesthetic Learner',
        'read-write': 'Read/Write Learner'
      };
      
      const descriptions = {
        visual: 'You learn best through visual aids, diagrams, and charts.',
        auditory: 'You learn best through listening, discussion, and verbal instruction.',
        kinesthetic: 'You learn best through hands-on activities and movement.',
        'read-write': 'You learn best through reading and writing activities.'
      };
      
      onComplete(styleLabels[topStyle as keyof typeof styleLabels], descriptions[topStyle as keyof typeof descriptions]);
    }
  };

  const progress = ((currentQuestion + 1) / questions.length) * 100;

  return (
    <div className="space-y-4">
      <Progress value={progress} className="h-2" />
      <div className="space-y-4">
        <h4 className="font-medium">Question {currentQuestion + 1} of {questions.length}</h4>
        <p className="text-sm">{questions[currentQuestion].question}</p>
        <RadioGroup onValueChange={handleAnswer} value={answers[currentQuestion] || ""}>
          {questions[currentQuestion].options.map((option, index) => (
            <div key={index} className="flex items-center space-x-2">
              <RadioGroupItem value={option.value} id={`option-${index}`} />
              <Label htmlFor={`option-${index}`} className="cursor-pointer flex-1">
                {option.label}
              </Label>
            </div>
          ))}
        </RadioGroup>
      </div>
    </div>
  );
}

// Simple Strengths Discovery Assessment Component
function StrengthsDiscoveryAssessment({ onComplete }: { onComplete: (result: string, description: string, details: string[]) => void }) {
  const [answers, setAnswers] = useState<Record<string, number>>({});

  const statements = [
    { key: 'analytical', text: 'I enjoy solving logic puzzles or analyzing data' },
    { key: 'collaborative', text: 'I learn better when I can explain ideas to others' },
    { key: 'creative', text: 'I like coming up with creative solutions' },
    { key: 'helpful', text: 'I often help classmates with their work' },
    { key: 'systematic', text: 'I prefer organized, step-by-step approaches' }
  ];

  const handleAnswer = (key: string, value: number) => {
    setAnswers(prev => ({ ...prev, [key]: value }));
  };

  const handleSubmit = () => {
    const strengthLabels = {
      analytical: 'Logical Thinking',
      collaborative: 'Teamwork',
      creative: 'Creative Problem Solving',
      helpful: 'Mentoring',
      systematic: 'Organization'
    };

    const topStrengths = Object.entries(answers)
      .filter(([_, score]) => score >= 4)
      .map(([key, _]) => strengthLabels[key as keyof typeof strengthLabels])
      .slice(0, 4);

    onComplete(
      'Strengths Profile Complete',
      `Your top strengths have been identified based on your responses.`,
      topStrengths
    );
  };

  const allAnswered = statements.every(stmt => answers[stmt.key] !== undefined);

  return (
    <div className="space-y-6">
      <p className="text-sm text-muted-foreground">Rate each statement from 1 (Strongly Disagree) to 5 (Strongly Agree)</p>
      {statements.map((statement) => (
        <div key={statement.key} className="space-y-2">
          <p className="text-sm">{statement.text}</p>
          <RadioGroup 
            value={answers[statement.key]?.toString() || ""} 
            onValueChange={(value) => handleAnswer(statement.key, parseInt(value))}
          >
            <div className="flex gap-4">
              {[1, 2, 3, 4, 5].map((num) => (
                <div key={num} className="flex items-center space-x-1">
                  <RadioGroupItem value={num.toString()} id={`${statement.key}-${num}`} />
                  <Label htmlFor={`${statement.key}-${num}`} className="text-xs">{num}</Label>
                </div>
              ))}
            </div>
          </RadioGroup>
        </div>
      ))}
      <Button onClick={handleSubmit} disabled={!allAnswered} className="w-full">
        View My Strengths
      </Button>
    </div>
  );
}

// Simple Interest Explorer Assessment Component  
function InterestExplorerAssessment({ onComplete }: { onComplete: (result: string, description: string) => void }) {
  const [answers, setAnswers] = useState<Record<string, boolean>>({});

  const questions = [
    { key: 'social', text: 'I like working with people and helping others' },
    { key: 'investigative', text: 'I enjoy experimenting or exploring how things work' },
    { key: 'artistic', text: 'I often draw, write, or imagine new things' },
    { key: 'realistic', text: 'I prefer solving real-world problems with others' },
    { key: 'enterprising', text: 'I like leading groups and organizing activities' },
    { key: 'conventional', text: 'I work well with clear instructions and systems' }
  ];

  const handleAnswer = (key: string, value: boolean) => {
    setAnswers(prev => ({ ...prev, [key]: value }));
  };

  const handleSubmit = () => {
    const categoryLabels = {
      social: 'Social',
      investigative: 'Investigative', 
      artistic: 'Artistic',
      realistic: 'Realistic',
      enterprising: 'Enterprising',
      conventional: 'Conventional'
    };

    const positiveAnswers = Object.entries(answers)
      .filter(([_, value]) => value === true)
      .map(([key, _]) => categoryLabels[key as keyof typeof categoryLabels]);

    const topCategories = positiveAnswers.slice(0, 2);
    const result = topCategories.length > 1 
      ? `${topCategories[0]}-${topCategories[1]} Profile`
      : `${topCategories[0] || 'Balanced'} Profile`;

    onComplete(
      result,
      `Your interests align most with ${topCategories.join(' and ')} activities and learning paths.`
    );
  };

  const allAnswered = questions.every(q => answers[q.key] !== undefined);

  return (
    <div className="space-y-4">
      <p className="text-sm text-muted-foreground">Answer Yes or No to each statement</p>
      {questions.map((question) => (
        <div key={question.key} className="space-y-2">
          <p className="text-sm">{question.text}</p>
          <RadioGroup 
            value={answers[question.key]?.toString() || ""} 
            onValueChange={(value) => handleAnswer(question.key, value === 'true')}
          >
            <div className="flex gap-4">
              <div className="flex items-center space-x-2">
                <RadioGroupItem value="true" id={`${question.key}-yes`} />
                <Label htmlFor={`${question.key}-yes`}>Yes</Label>
              </div>
              <div className="flex items-center space-x-2">
                <RadioGroupItem value="false" id={`${question.key}-no`} />
                <Label htmlFor={`${question.key}-no`}>No</Label>
              </div>
            </div>
          </RadioGroup>
        </div>
      ))}
      <Button onClick={handleSubmit} disabled={!allAnswered} className="w-full">
        Explore My Interests
      </Button>
    </div>
  );
}
